<template>
  <div class="heard">
    <div class="content">
      <div class="logo">
        <router-link to='/'>
          <img src="../assets/static/t-01.png" />
        </router-link>
      </div>
      <div class="right-header">
        <el-autocomplete class="uni-input" v-model="searchInput" :fetch-suggestions="querySearch" placeholder="输入搜索店铺" @input="searchInput = searchInput.replace(/\s*/g,'')" @select="handleInputSelect">
        </el-autocomplete>
        <span class="search"></span>
      </div>
      <div class="right-header">
        <div class="right-header-item"><span class="phone"></span>手机端下载</div>
        <div class="right-header-item">了解我们<span class="info"></span></div>
        <div class="right-header-item">|</div>
        <div class="right-header-item" @click="toggle()" v-if="!userInfo.userInfo">玩家登录</div>
        <div class="right-header-item-list" v-if="userInfo.userInfo">
          <span class="logto">
            <img src="../assets/static/t-14.png" />
            {{userInfo.userInfo.nickName}}
          </span>
          <div class="dropdown-menu">
            <div class="logout">
              <router-link tag="a" target="_blank" :to="{path:'./my'}">个人中心</router-link>
            </div>
            <div @click="logout()" class="logout">退出</div>
          </div>
        </div>
        <div class="right-header-item">商家登录</div>
      </div>
      <!-- 注册登录 -->
      <div class="uni-popup" v-show="uniPopup">

        <!-- 登录 -->
        <div class="login" v-show="is_login_register">
          <div class="close" @click="close">×</div>
          <div :class="!is_scan_pc?'login-wx-user':'login-pc-user'" @click="BindLoginUser">
            <span v-if="!is_scan_pc" class="saoma">微信扫码登录</span>
          </div>
          <div v-show="is_scan_pc">
            <div id="weixinLogin" v-show="is_bing_phone"></div>
            <div v-show="!is_bing_phone">
              <h1 class="bingphone">绑定手机号</h1>
              <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
                <el-form-item prop="mobile">
                  <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input class="input" style="width:63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                  <div class="codephone" @click="getLoginCode" v-if='isCodeShow'>{{codespan}}</div>
                  <div class="codephone del" v-if='!isCodeShow'>{{codespan}}</div>
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">登录/注册</el-button>
            </div>

          </div>
          <div v-show="!is_scan_pc">
            <div class="login-title">
              <span @click="bindSms(true)" :class="is_sms_password?'atv':''">短信登录</span>
              <span @click="bindSms(false)" :class="!is_sms_password?'atv':''">密码登录</span>
            </div>

            <div v-if="is_sms_password">
              <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
                <el-form-item prop="mobile">
                  <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input class="input" style="width:63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                  <div class="codephone" @click="getLoginCode" v-if='isCodeShow'>{{codespan}}</div>
                  <div class="codephone del" v-if='!isCodeShow'>{{codespan}}</div>
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">登录/注册</el-button>
            </div>

            <div v-if="!is_sms_password">
              <el-form ref="formloginUser" :model="formloginUser" :rules="rulesUser">
                <el-form-item prop="username">
                  <el-input v-model="formloginUser.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="formloginUser.password" placeholder="请输入密码" @keyup.enter.native="loginUserSubmit" />
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" @click="loginUserSubmit">登录</el-button>
              <div class="agreement">
                <span>登录或注册代表您已阅读并接受</span>
                <router-link to='/'>《用户协议》</router-link>

                <router-link to='/'>《隐私政策》</router-link>
              </div>
              <div class="click-register">
                没有账号？
                <span @click="userLogin()">点击注册</span>
              </div>
            </div>
          </div>

        </div>
        <!-- 注册 -->
        <div class="login" v-show="!is_login_register">
          <div class="close" @click="close">×</div>
          <div class="login-title-red">注册账户</div>
          <el-form ref="form" :model="formData" :rules="rules">
            <el-form-item prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="formData.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input class="input" style="width:58%" v-model="formData.code" placeholder="手机验证码" />
              <div class="codephone" @click="getRegisterCode" v-if='registerisCodeShow'>{{registercodespan}}</div>
              <div class="codephone del" v-if='!registerisCodeShow'>{{registercodespan}}</div>
            </el-form-item>

          </el-form>
          <el-button class="userLogin" :loading="loading" @click="submit">注册</el-button>
          <div class="agreement">
            <span>登录或注册代表您已阅读并接受</span>
            <router-link to='/'>《用户协议》</router-link>
            <router-link to='/'>《隐私政策》</router-link>
          </div>
          <div class="click-register">
            <span @click="userLogin()">点击登录</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
export default {
  data () {
    return {
      searchInput: '',
      uniPopup: false,
      userInfo: '',
      time: null,
      registercodespan: '获取验证码',
      registerTime: null,
      registerisCodeShow: true,
      codespan: '获取验证码',
      isCodeShow: true,
      is_bing_phone: true, // 微信登录绑定手机
      is_login_register: true, // 登录或注册
      is_scan_pc: true, // 扫码或账号登录
      is_sms_password: true, // 短信登录或密码登录
      loading: false,
      formloginPone: {
        // 手机登录数据
        mobile: '',
        code: '',
        wxopenid: ''
      },

      formloginUser: {
        // 用户名登录数据
        username: '',
        password: ''
      },

      formData: {
        // 注册数据
        username: '',
        password: '',
        mobile: '',
        code: ''
      },
      rulesUser: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少 6个字符'
          }
        ]
      },
      rulesPhone: {
        // 数据校验
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|6|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少 4 个字符'
          }
        ]
      },
      rules: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少6 个字符'
          }
        ],

        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|6|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少4个字符'
          }
        ]
      }
    }
  },
  watch: {
    // $route:{
    //   handler(val,oldval){
    //     if(val.query.code&&!localStorage.getItem("token")){
    // 		console.log(val.query.code)
    // 		this.loginByScanWeixin(val.query.code)
    // 		this.$router.replace({path:'/'})
    // 	}
    //   },
    //   // 深度观察监听
    //   deep: true
    // }
  },
  computed: {},
  mounted () {
    //   this.$apis.getInfo().then(res=>{
    // 	console.log(res)
    //   })

    this.getRoutes()
    this.getLogin()
    const u = localStorage.getItem('storage_key')
    if (u) {
      this.userInfo = JSON.parse(u)
    }
  },

  methods: {
    handleInputSelect (e) {
      console.log(e)
    },
    querySearch (queryString, cb) {
      console.log(queryString)
      var restaurants = [{ value: '手动阀手动阀' }]
      // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(restaurants)
      }, 3000 * Math.random())
    },
    //   createStateFilter(queryString) {
    //     return (state) => {
    //       return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
    //     };
    //   },
    getLogin () {
      // 微信登录
      var http = 'https://api.fengwg.com/geem2/redirect?url='
      var callback = 'http%3A%2F%2Flocalhost%3A8080%2F%23%2F'
      // 微信登录实例JS对象
      const object = new WxLogin({
        self_redirect: false,
        // 页面中对应展示二维码的容器ID
        id: 'weixinLogin',
        appid: 'wxca3633ca971bd815',
        scope: 'snsapi_login',
        // 回调地址
        redirect_uri: encodeURIComponent(http + callback),
        // 若在业务中需要有多个判定参数 可以通过拼接的方式放在 state 中
        state: Math.random(),
        style: 'black',
        // 二维码样式及其它（关于样式自定义可在网上查阅到相关的实现）
        href:
          'data:span/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDMxMnB4O2hlaWdodDozMTJweDtib3JkZXI6IG5vbmUgIWltcG9ydGFudDttYXJnaW4tdG9wOiAwICFpbXBvcnRhbnQ7fQouaW1wb3dlckJveCAudGl0bGUge2Rpc3BsYXk6IG5vbmU7fQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIwMHB4O30KLnN0YXR1c19pY29uIHtkaXNwbGF5OiBub25lfQouaW1wb3dlckJveCAuc3RhdHVzIHt0ZXh0LWFsaWduOiBjZW50ZXI7fSAKLmxvZ2luX2NvbnRhaW5lcntoZWlnaHQ6MjEwcHg7fQouaW5mb3tkaXNwbGF5OiBub25lO30KLmxvZ2luUGFuZWwge3Bvc2l0aW9uOiBhYnNvbHV0ZTt0b3A6IC0xNHB4OyBsZWZ0OiAycHg7fQoudGl0bGV7CglkaXNwbGF5OiBub25lICFpbXBvcnRhbnQ7Cn0KLmluZm8gewoJZGlzcGxheTogbm9uZSAhaW1wb3J0YW50Owp9Cg=='
      })
    },
    getLoginCode () {
      // 获取登录验证码

      this.$refs.formloginPone.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.time)
          let numberTime = 60
          this.isCodeShow = false
          this.time = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.time)
              this.codespan = '获取验证码'
              this.isCodeShow = true
              return
            }
            this.codespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formloginPone.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    getRegisterCode () {
      // 获取注册验证码
      this.$refs.form.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.registerTime)
          let numberTime = 60
          this.registerisCodeShow = false
          this.registerTime = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.registerTime)
              this.registercodespan = '获取验证码'
              this.registerisCodeShow = true
              return
            }
            this.registercodespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formData.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    submit () {
      // 注册
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .register({
              code: this.formData.code,
              mobile: this.formData.mobile,
              password: this.formData.password,
              username: this.formData.username
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('注册成功')
                this.userInfo = res.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },

    loginByScanWeixin (e) {
      // 微信扫码登录
      this.$apis
        .loginByScanWeixin({
          code: e
        })
        .then(res => {
          if (res.data.errno == 0) {
            const data = res.data.data
            if (data.token) {
              this.$message.success('登录成功')
              this.userInfo = data
              this.init(data)
            } else {
              this.formloginPone.wxopenid = data.openId
              this.uniPopup = true
              this.is_bing_phone = false
            }
          } else {
            this.$message.error(res.data.errmsg)
          }
        })
    },
    loginPhoneSubmit () {
      // 手机登录
      this.$refs.formloginPone.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis.loginbymobile(this.formloginPone).then(res => {
            this.loading = false
            if (res.data.errno == 0) {
              this.$message.success('登录成功')
              this.userInfo = res.data.data
              this.init(res.data.data)
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
        }
      })
    },
    loginUserSubmit () {
      // 用户名登录

      this.$refs.formloginUser.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .login({
              password: this.formloginUser.password,
              username: this.formloginUser.username
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('登录成功')
                this.userInfo = res.data.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    logout () {
      // 退出
      this.$apis.logout().then(res => {
        if (res.data.errno == 0) {
        }
        this.userInfo = ''
        localStorage.removeItem('storage_key')
        localStorage.removeItem('token')
        this.$store.commit('setUserInfo', '')
      })
    },

    getRoutes () {
      if (!this.$route.meta.pagePath) {
      }
    },

    toggle () {
      this.uniPopup = true
    },
    close () {
      this.uniPopup = false
      this.uniPopup = false
      this.is_scan_pc = true
      this.is_bing_phone = true
      this.formloginPone.wxopenid = ''
      this.formloginPone.mobile = ''
      this.formloginPone.code = ''
      this.formloginUser.username = ''
      this.formloginUser.password = ''
      this.formData.username = ''
      this.formData.password = ''
      this.formData.mobile = ''
      this.formData.code = ''
    },
    init (e) {
      this.close()
      localStorage.setItem('token', e.token)
      this.$store.commit('setUserInfo', e)
      localStorage.setItem('storage_key', JSON.stringify(e))
    },
    userLogin () {
      this.is_login_register = !this.is_login_register
      this.$refs.form.clearValidate()
    },
    BindLoginUser () {
      this.is_scan_pc = !this.is_scan_pc
    },
    bindSms (e) {
      if (this.is_sms_password == e) {
        return
      }
      if (e) {
        this.$refs.formloginUser.clearValidate()
      } else {
        this.$refs.formloginPone.clearValidate()
      }

      this.is_sms_password = e
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.logo {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex: 1;
}

.logo img {
  height: 32px;
  width: 88px;
}

.logo span {
  margin-left: 16px;
}

.phone {
  background: url("../assets/static/t-02.png") no-repeat left center;
  background-size: 18px 22px;
  display: inline-block;
  width: 18px;
  height: 22px;
  vertical-align: sub;
  margin-right: 10px;
}
.info {
  background: url("../assets/static/t-04.png") no-repeat left center;
  background-size: 9px 6px;
  display: inline-block;
  width: 9px;
  height: 6px;
  vertical-align: middle;
  margin-left: 10px;
}

.uni-input {
  width: 437px;
  height: 40px;
  box-sizing: border-box;
  background: #f3f4f5;
  border: 1px solid #f3f4f5;
  border-radius: 22px;
  padding: 0px 20px;
}
.search {
  background: url("../assets/static/t-03.png") no-repeat left center;
  background-size: 20px 20px;
  display: inline-block;
  width: 20px;
  height: 40px;
  margin-left: 10px;
}

.forget-password {
  span-align: right;
  color: #3377aa;
  cursor: pointer;
}
.forget-password:hover {
  color: #da2740;
}
.userLogin {
  background: #da2740;
  color: #fff;
  margin: 15px 0;
  width: 100%;
}
uni-navigator {
  display: inline;
  color: #3377aa;
}
.click-register {
  text-align: right;
  margin: 25px 0 10px;
  span {
    color: #3377aa;
    cursor: pointer;
  }
}

.heard {
  height: 80px;
  background: #ffffff;
  box-shadow: 0px 4px 19px 1px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: row;
  ustify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  margin-bottom: 30px;
}
</style>
